import { GraphicsGroupItem } from "@/config/graphicsGroup.ts";
import React, { useEffect, useState } from "react";
import localforage from "localforage";
import axios from "@/utils/request.ts";
import { Collapse } from "antd";
import { FolderOutlined, LoadingOutlined } from "@ant-design/icons";
import styles from "@/layout/Graphics/Graphics.module.scss";
import { deepClone } from "@meta2d/core";
import { registerDraw } from "@/utils/registerDraw.js";
function JsCom({ item }: { item: GraphicsGroupItem }) {
  const [list, setList] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const requestList = () => {
    return new Promise((resolve, reject) => {
      if (item.api != null) {
        axios
          .get(item.api)
          .then((r) => {
            resolve(r.data);
          })
          .catch(() => {
            resolve([]);
          })
          .finally(() => {
            setLoading(false);
          });
      } else {
        reject([]);
      }
    });
  };
  const dragStart = (e: React.MouseEvent<HTMLDivElement>, elem: any) => {
    if (!elem) {
      return;
    }
    e.stopPropagation();
    elem.data = {
      ...elem.data,
      width: elem.data?.rect?.width * 5,
      height: elem.data?.rect?.height * 5,
    };
    // 拖拽事件
    if (e instanceof DragEvent) {
      // 设置拖拽数据
      e.dataTransfer?.setData("Meta2d", JSON.stringify(elem.data));
    } else {
      // 支持单击添加图元。平板模式
      window.meta2d.canvas.addCaches = deepClone([elem.data]);
    }
  };
  useEffect(() => {
    localforage.getItem(item.key).then((value) => {
      if (value == null || (value as any[]).length <= 0) {
        requestList().then((data) => {
          setList(() => data as any[]);
          localforage.setItem(item.key, data);
        });
      } else {
        setList(() => value as any[]);
        setLoading(false);
      }
    });
  }, []);
  useEffect(() => {
    if (list.length > 0) {
      list.forEach((item) => {
        registerDraw(item);
      });
    }
  }, [list]);
  return (
    <>
      <Collapse
        style={{ border: "none", borderRadius: 0, borderColor: "#000000" }}
        expandIconPosition={"end"}
        items={[
          {
            key: "panel",
            label: (
              <>
                {loading ? (
                  <LoadingOutlined style={{ marginRight: 5 }} />
                ) : (
                  <FolderOutlined style={{ marginRight: 5 }} />
                )}
                {`${item.key} (${list.length})`}
              </>
            ),
            children: (
              <div className={styles.GraphicsItem}>
                {list.map((_listItem, index) => {
                  return (
                    <div
                      draggable={true}
                      key={_listItem.name + index + ""}
                      title={_listItem.name}
                      className="item"
                      onDragStart={(event) => dragStart(event, _listItem)}
                      onClick={(event) => dragStart(event, _listItem)}
                    >
                      <CustomizeIcon icon={_listItem.svg}></CustomizeIcon>
                    </div>
                  );
                })}
              </div>
            ),
            style: {
              borderRadius: 0,
            },
          },
        ]}
        defaultActiveKey={[]}
      ></Collapse>
    </>
  );
}
function CustomizeIcon({ icon }: { icon: string }) {
  return (
    <>
      <span
        style={{ color: "#ffffff" }}
        dangerouslySetInnerHTML={{ __html: icon }}
      ></span>
    </>
  );
}
export default React.memo(JsCom);
